import { Button, Form, Input } from 'antd-mobile'
import http from '../../api/index'
import Djs from '../../hooks/UseDjs'
import { useEffect, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import style from './index.module.css'
function Index() {
  const [num, fn, disable] = Djs()
  const [from] = Form.useForm()
  // 保存待回显的验证码，等待倒计时结束后再写入表单
  const pendingCodeRef = useRef<string | null>(null)
  const nav = useNavigate()
  const yzm = async () => {
    const yzms = await from.validateFields(['phone'])
    const { data: res } = await http.post('/api/login', { phone: yzms.phone })
    console.log(res.data);
    // 先清空输入框，待倒计时结束后再回显
    pendingCodeRef.current = res.data
    from.setFieldsValue({ code: '' })
    fn()
  }
  // 当倒计时结束（按钮从禁用变为可用）后，将验证码回显到表单
  useEffect(() => {
    if (!disable && pendingCodeRef.current) {
      from.setFieldsValue({ code: pendingCodeRef.current })
      pendingCodeRef.current = null
    }
  }, [disable, from])

  const onFinish = async (values: any) => {
    const { data: ref } = await http.post('/api/login', values)
    console.log(ref)
    nav('/home')
  }
  return (
    <div>
      <div className={style.loginContainer}>
        <div className={style.loginCard}>
          <h3 className={style.loginTitle}>请使用手机号登录</h3>
          <Form
            form={from}
            onFinish={onFinish}
            layout='horizontal'

            footer={
              <Button block type='submit' color='primary' size='large'>
                提交
              </Button>
            }
          >
            <Form.Item
              label='手机号'
              name='phone'
              rules={[
                {
                  required: true, message: '姓名不能为空'
                },
                {
                  pattern: /^1[3-9]\d{9}$/,
                  message: '请输入正确的手机号'
                }
              ]}
            >
              <Input placeholder='请输入' />
            </Form.Item>
            <Form.Item label='验证码'
              name='code'
              extra={<Button onClick={yzm} disabled={disable}>{
                disable ? `获取验证码(${num})` : '发验证码'
              }</Button>}
              rules={[
                {
                  required: true, message: '姓名不能为空'
                },
              ]}
            >
              <Input placeholder='请输入' />
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  )
}

export default Index
